const daySpan = 24 * 60 * 60 * 1000;

/* 
	判断闰年
 */
function isLeapYear(year) {
	if(year / 4 == 0 && year / 100 != 0){
	  return true;
  } else if (year / 400 == 0){
	  return true;
	} else{
	  return false;
  }
}

/* 
	获取某年某月天数
 */
function getMonthDays(year, month) {
	switch (month) {
	  case 1:
	  case 3:
	  case 5:
	  case 7:
	  case 8:
	  case 10:
	  case 12:
	    return 31;
	  case 4:
	  case 6:
	  case 9:
	  case 11:
	    return 30;
	  case 2:
	    return isLeapYear(year) ? 29 : 28;
		default:
			return 0;
	}
}

/* 
	获取某年某月信息
 */
function getMonthInfo(year, month) {
	const monthDate = new Date(`${year}-${month}-1`);
	const days = getMonthDays(year, month);
	const firstDay = monthDate.getDay();
	const info = [];
	let index = 0;
	while(index < days) {
		info.push({
			year,
			month,
			date: index + 1,
			day: (index + firstDay) % 7,
			week: Math.ceil((index + firstDay) / 7),
			value: monthDate.valueOf() + index * daySpan
		})
		index = index + 1;
	}
	return info;
}

/* 
	获取按日历填充的完整的某年某月信息
 */
function getMonthCalendar(year, month, startDay = 0) {
	const currentMonthInfo = getMonthInfo(year, month);
	currentMonthInfo.forEach(item => item.calendar = 0);
	const prevHolder = Math.abs(currentMonthInfo[0].day - startDay);
	const nextHolder = 42 - prevHolder - currentMonthInfo.length;
	const prevLastDate = new Date(currentMonthInfo[0].value);
	const nextFirstDate = new Date(currentMonthInfo[currentMonthInfo.length - 1].value);
	prevLastDate.setDate(0);
	const prevMonthInfo = getMonthInfo(prevLastDate.getFullYear(), prevLastDate.getMonth() + 1);
	nextFirstDate.setDate(nextFirstDate.getDate() + 1);
	const nextMonthInfo = getMonthInfo(nextFirstDate.getFullYear(), nextFirstDate.getMonth() + 1);
	return [
		...prevMonthInfo.splice(-prevHolder, prevHolder).map(item => {
			item.calendar = -1;
			return item;
		}),
		...currentMonthInfo.map(item => {
			item.calendar = 0;
			return item;
		}),
		...nextMonthInfo.splice(0, nextHolder).map(item => {
			item.calendar = 1;
			return item;
		})
	]
}

/* 
	获取按日历7天一行排列填充的完整的某年某月信息
 */
function getPartMonthCalendar(year, month, startDay = 0) {
	const calendarList = getMonthCalendar(year, month, startDay);
	const parts = [];
	for(let i = 0; i < 6; i++) {
		parts.push(calendarList.slice(i * 7, (i + 1) * 7));
	}
	return parts;
}

export {
	isLeapYear,
	getMonthDays,
	getMonthInfo,
	getMonthCalendar,
	getPartMonthCalendar
}